package com.demo.common.redis.component;

import com.demo.common.redis.exception.RedisException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

@Slf4j
public class RedisKeys {

    private final Environment environment;

    public static String appName;

    public RedisKeys(Environment environment){
        this.environment = environment;
    }


    // 幂等性
    public static String REDIS_IDEMPOTENCE;

    // 接口幂等性
    public static String REDIS_API_IDEMPOTENCE;

    // 分布式锁
    public static String REDIS_DISTRIBUTE_LOCK;

    // 用户Api 限流
    public static String USER_API_LIMIT;

    // 用户webSite
    public static String USER_WEB_LIMIT;

    @PostConstruct
    public void init() {
        appName = environment.getProperty("spring.application.name");
        if (!StringUtils.hasText(appName)) {
            throw new RedisException("请为当前应用设置 [spring:application:name]属性");
        }
        REDIS_IDEMPOTENCE = appName + ":redis_idempotence";
        REDIS_API_IDEMPOTENCE = appName + ":redis_api_idempotence";
        REDIS_DISTRIBUTE_LOCK = appName + ":redis_distribute_lock";
        USER_API_LIMIT = appName + ":user_api_limit";
        USER_WEB_LIMIT = appName + ":user_web_limit";
    }
    public static String getRedisApiIdempotentKey(String username,String className, String methodName,String extra) {
        String s = RedisKeys.REDIS_API_IDEMPOTENCE + ":" + username + ":" + className + "#" + methodName;
        if (StringUtils.hasText(extra)) {
            s += "(" + extra + ")";
        }
        return s;
    }

    public static String getRedisDistributeLockKey(String className, String methodName,String extra) {
        String s = RedisKeys.REDIS_DISTRIBUTE_LOCK + ":" + className + "#" + methodName;
        if (StringUtils.hasText(extra)) {
            s += "(" + extra + ")";
        }
        return s;
    }

    public static String userApiLimit(String usernameOrIp ,String clazzName,String methodName){
        return USER_API_LIMIT + ":" + usernameOrIp + ":" + clazzName + "#" + methodName;
    }

    public static String userWebLimit(String usernameOrIp){
        return USER_WEB_LIMIT + ":" + usernameOrIp;
    }
}
